// 导入数据库模块
const db = require('../db/index.js')
var bcrypt = require('bcryptjs')//引入加密算法
var salt = bcrypt.genSaltSync(10)
// 引入jwt解析token
const jwt = require('jsonwebtoken')
const {jwtSecretKey} = require('../config/index.js')

// 注册接口功能
function reguser(req, res) {
    // 1.接收传入数据
    let { username, password } = req.body
    if (!username || !password)
        // 使用处理错误中间件
        return res.cc('username与password为必传项')
    // 2.检测用户是否被占用
    const selectSql = `select * from ev_users where username = ?`
    db.query(selectSql, username, function (err, results) {
        if (err)
            return res.cc(err)
        if (results.length >= 1)
            return res.cc('当前用户已注册')

        // 3.加密密码
        password = bcrypt.hashSync(password, salt)
        // 4.插入新用户
        const inserSql = `insert into ev_users (username,password) value(?,?)`
        db.query(inserSql, [username, password], function (err, results) {
            if (err || results.affectedRows !== 1)
                return res.cc(err)
            res.send({
                status: 201,
                message: '注册成功'
            })
        })
    })
}

// 登录接口功能
function login(req, res) {
    // 检查表单数据是否合法，joi在路由中帮我们做好了
    let  {username, password} = req.body
    
    const selectSql = `select * from ev_users where username=?`
    db.query(selectSql,username, function (err, results) {
        if (err) return res.cc(err)
        // 对比用户密码是否和数据中一致
        let user = results[0]
        console.log(user,2222)
        let db_password = results[0].password
        let compareSyncResult = bcrypt.compareSync(password, db_password)
        if (!compareSyncResult) return res.cc('密码和账户不匹配')
        //生成jwt的token字符串
        delete user.password
        let token = jwt.sign(
            {...user},
            jwtSecretKey,
            { expiresIn: '7d' }//过期时间
        )
        // 匹配成功
        res.send({
            status: 200,
            message: '校验成功',
            token:'Bearer ' + token
        })
    })
}



// 导出
module.exports = {
    reguser,
    login
}